package servlet;

import dao.UserMapper;
import entity.User;
import enum_var.UserRole;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpSession;
import utils.MyBatisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSession;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
@MultipartConfig
public class LoginServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {

            String username = request.getParameter("username");
            String password = request.getParameter("password");
            System.out.println("username: " + username + ", password: " + password);
            if (username == null || username.trim().isEmpty() || 
                password == null || password.trim().isEmpty()) {
                throw new Exception("用户名和密码不能为空");
            }

            try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                User user = userMapper.selectByUsernameAndPassword(username, password);

                if (user == null) {
                    throw new Exception("用户名或密码错误");
                }

                // 登录成功，保存用户信息到会话
                HttpSession session = request.getSession();
                session.setAttribute("userId", user.getId());
                session.setAttribute("username", user.getUsername());
                session.setAttribute("role", user.getRole().name());

                result.put("success", true);
                result.put("message", "登录成功");
                result.put("role", user.getRole().name());
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 退出登录
        HttpSession session = request.getSession();
        session.invalidate();
        response.sendRedirect(request.getContextPath() + "/login.html");
    }
}
